/**
 * Created by zhoulin on 2019/4/3.
 */
var interval = [];
var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
var app = new Vue({
    el: '#app',
    data: {
        permissions:['staff:add','staff:update','department:list','station:list'],
        identify:"@",//账号标识
        passText:"随机生成",//密码生成按钮名称
        isShow:0,
        createAccountText:"创建登录账号",
        deptPerms:false,
        roles:false,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if(empty(token)){
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon:5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            },1200)

            return ;
        }
        that.getStation();
        that.getDictionary();
        that.getDeptPerms();
        that.getRoles();
        if(!empty(aGET.id)){
            that.init();
        }

    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        //解决修改时候数据不及时更新问题
        init:function () {
            var that = this;
            if(Boolean(that.roles) && Boolean(that.deptPerms)){
                for (var itme in interval){
                    window.clearInterval(interval[itme]);
                }
                that.getInfoById(aGET.id);
            }else {
                interval.push(
                    window.setInterval(function () {
                    that.init();
                },1000))
            }
        },
        getInfoById:function (id) {
            var that = this;
            //$("#Form #createAccount input[name='createAccount']").attr("checked","checked");
            //that.isShow = 1;
            that.createAccountText="修改登录账号";
            Get(that,_HOST+_API.business_manage_staff_getInfoById+id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response.data)
                    if(response){
                        if(response.success){
                            var list = response.data
                            for (var item in list) {
                                if("sex" == item || "stationId" == item || "headerImgUrl" == item || "wxImgUrl" == item || "username" == item || "businessRoleList" == item || "deptPermissionList" == item){
                                    continue ;
                                }
                                $("#Form input[name='" + item + "']").val(list[item]);
                            }
                            $("#Form select[name='sex']").val(list["sex"]);
                            $("#Form select[name='stationId']").val(list["stationId"]);
                            if(!empty(list["headerImgUrl"])){
                                $("#headerImgUrl").attr("src",list["headerImgUrl"]);
                            }
                            if(!empty(list["wxImgUrl"])){
                                $("#wxImgUrl").attr("src",list["wxImgUrl"]);
                            }
                            $("#Form input[name='username']").val(list["username"].replace(that.identify,""));
                            that.passText = "重置密码";
                            $("#Form input[name='password']").attr("readonly","readonly");

                            for (var item in list["deptPermissionList"]){
                                $("#deptPerms input[name='deptPerm'][value='" + list["deptPermissionList"][item].deptId + "']").iCheck('check');
                            }

                            for (var item in list["businessRoleList"]){
                                $("#roles input[name='role'][value='" + list["businessRoleList"][item].rid + "']").iCheck('check');
                            }

                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //获取字典表配置数据
        getDictionary:function () {
            var that = this;
            var params = "?keyTable=_IDENTIFY,sex"
            Get(that,_HOST+_API.common_dic_dicList+params)
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if(response){
                        if(response.success){
                            var list = response.list
                            var domOption = "";
                            for (var item in list) {
                                if("sex" == list[item].keyTable){
                                    domOption += "<option value='" + list[item].keyS + "'>" + list[item].keyValue + "</option>";
                                }
                                if("_IDENTIFY" == list[item].keyTable){
                                    if("accountIdentify" == list[item].keyS){
                                        that.identify = list[item].keyValue;
                                    }
                                }
                            }
                            $("#Form select[name='sex']").append(domOption);
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //获取当前机构职位
        getStation:function () {
            var that = this;
            var params = "?pageNumber=1&pageSize=100"
            Get(that,_HOST+_API.business_manage_station_list+params,that.permissions[3])
                .then(function (response) {
                    // 响应成功回调
                    if(response){
                        if(response.success){
                            var list = response.rows
                           // console.log(list)
                            var domOption = "";
                            for (var item in list) {
                                domOption += "<option value='" + list[item].id + "'>" + list[item].name + "</option>";
                            }
                            $("#Form select[name='stationId']").append(domOption);

                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //获取当前机构二级部门（校区）
        getDeptPerms:function () {
            var that = this;
            Get(that,_HOST+_API.business_manage_sysDepartment_secondList)
                .then(function (response) {
                    // 响应成功回调
                    if(response){
                            var html = "";
                            for (var item in response.list) {
                                html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" name="deptPerm" value="'+response.list[item].id+'"> '+response.list[item].name+'</label>'
                            }

                            $("#Form #deptPerms").append(html);
                            $("#deptPerms .i-checks").iCheck({checkboxClass: "icheckbox_square-green",radioClass: "iradio_square-green",});
                            that.deptPerms = true;
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                })
        },
        //获取当前机构角色
        getRoles:function () {
            var that = this;
            Get(that,_HOST+_API.business_manage_sysRole_getAllRole)
                .then(function (response) {
                    // 响应成功回调
                    if(response){
                            var html = "";
                            for (var item in response.list) {
                                html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" name="role" value="'+response.list[item].id+'"> '+response.list[item].name+'</label>'
                            }

                            $("#Form #roles").append(html);
                            $("#roles .i-checks").iCheck({checkboxClass: "icheckbox_square-green",radioClass: "iradio_square-green",});
                            that.roles = true;
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                })
        },
        //
        add:function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            param.username=param.username+that.identify;
            param.isCreateAccount = that.isShow;
            console.log(param)
            console.log(param.username.replace(that.identify,""))
            var deptPermissionList = [];
            $("#deptPerms input[name='deptPerm']:checked").each(function () {
                deptPermissionList.push({"deptId":$(this).val()})
            })
            var businessRoleList = [];
            $("#roles input[name='role']:checked").each(function () {
                businessRoleList.push({"rid":$(this).val()})
            })
            param.deptPermissionList = deptPermissionList;
            param.businessRoleList = businessRoleList;
            Post(that,_HOST+_API.business_manage_staff_add,param,true,that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        update:function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            param.username=param.username+that.identify;
            param.isCreateAccount = that.isShow;
            var deptPermissionList = [];
            $("#deptPerms input[name='deptPerm']:checked").each(function () {
                deptPermissionList.push({"deptId":$(this).val()})
            })
            var businessRoleList = [];
            $("#roles input[name='role']:checked").each(function () {
                businessRoleList.push({"rid":$(this).val()})
            })
            param.deptPermissionList = deptPermissionList;
            param.businessRoleList = businessRoleList;
            console.log(param)
            Put(that,_HOST+_API.business_manage_staff_update,param,true,that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        //随机生成密码
        createPass:function () {
            $("#Form input[name='password']").attr("disabled",false);
            this.passText = "随机生成";
            $("#password").val(RndNum(6));
        },
        //设置部门
        setDept:function () {
            var that = this;
            var loadingIndex = layer.load(2, { //icon支持传入0-2
                shade: [0.5, 'gray'], //0.5透明度的灰色背景
                content: '数据加载中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                }
            });
            var setting = {
                check: {
                    enable: true,
                    chkStyle: "radio",
                    radioType: "all"   //对所有节点设置单选
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: function (e, treeId, treeNode, clickFlag) {
                        console.log(treeNode)
                       // deptId = treeNode.id;
                       // $("#deptName").val(treeNode.name);
                        zTreee.checkNode(treeNode, !treeNode.checked, true);
                    }
                },
            },zTreee;
            var zNodes = [];
            Get(that,_HOST+_API.business_manage_sysDepartment_list+"/"+deptId,that.permissions[2])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            var html = '<ul id="treeDemo" class="ztree"></ul>';
                            var confirm = layer.confirm(html, {
                                title:"权限",
                                btn: ['确定', '取消'], //按钮
                                shadeClose: false,
                                area:['40%','98%']
                            }, function () {
                                console.log("确定")
                                //选中部门
                                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                                nodes = zTree.getCheckedNodes(true);
                                if (nodes.length <= 0) {
                                    parent.layer.msg('请选择部门！', {time: 1500, icon: 5});
                                    return;
                                }

                                $("#deptId").val(nodes[0].id);
                                $("#deptName").val(nodes[0].name);
                                //单独清除某个字段验证
                                $('#Form').data('bootstrapValidator').enableFieldValidators('deptName', false);

                                layer.close(confirm);

                            });

                            zTreee = $.fn.zTree.init($("#treeDemo"), setting, response.list);
                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");

                            var nodes = treeObj.getNodes();
                            if (nodes.length>0) {
                                for(var i=0;i<nodes.length;i++){
                                    treeObj.expandNode(nodes[i], true, false, false);//默认展开第一级节点
                                }
                            }
                            layer.close(loadingIndex);
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //设置头像
        setImg:function () {
            var that = this;
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.uploadFile.requstUrl,_HOST+_API.common_file_ossUploadBase64FileStr);
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.loginPath,_LOGIN_PAGE);
            var index = layer.open({
                type: 2,
                title: "新增",
                content: "../../../../../../public-tools/pc/html/img-cropper.html",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
                end:function(){//关闭后调用的事件
                    var headerImgUrl = sessionStorageUtils.getJson(storageKey.sessionStorageKey.uploadFile.showUrl);
                    var imgId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.uploadFile.attachmentId);
                    if((!empty(headerImgUrl)) && (!empty(imgId))){
                        $("#headerImgUrl").attr("src",headerImgUrl);
                        $("#imgId").val(imgId);
                        sessionStorageUtils.del(storageKey.sessionStorageKey.uploadFile.showUrl)
                        sessionStorageUtils.del(storageKey.sessionStorageKey.uploadFile.attachmentId)
                    }
                }
            });
            layer.full(index);
        },
        //设置微信二维码
        setWxImg:function () {
            var that = this;
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.uploadFile.requstUrl,_HOST+_API.common_file_ossUploadBase64FileStr);
            var index = layer.open({
                type: 2,
                title: "新增",
                content: "../../../../../../public-tools/pc/html/img-cropper.html",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
                end:function(){//关闭后调用的事件
                    var wxImgUrl = sessionStorageUtils.getJson(storageKey.sessionStorageKey.uploadFile.showUrl);
                    var wxImg = sessionStorageUtils.getJson(storageKey.sessionStorageKey.uploadFile.attachmentId);
                    if((!empty(wxImgUrl)) && (!empty(wxImg))){
                        $("#wxImgUrl").attr("src",wxImgUrl);
                        $("#wxImg").val(wxImg);
                        sessionStorageUtils.del(storageKey.sessionStorageKey.uploadFile.showUrl)
                        sessionStorageUtils.del(storageKey.sessionStorageKey.uploadFile.attachmentId)
                    }
                }
            });
            layer.full(index);
        },
    },
})

/**
 * 是否创建登录账号
 */
$("#createAccount input:checkbox[name='createAccount']").on('ifChecked', function(event){
    //选中表示创建
    app.isShow = 1;
    $("#Form").data('bootstrapValidator').destroy();
    $('#Form').data('bootstrapValidator', null);
    Validator();
    if(empty(aGET.id)){
        $("#Form input[name='username']").val($("#Form input[name='name']").val());
        $("#Form input[name='nickname']").val($("#Form input[name='name']").val());
    }
});
$("#createAccount input:checkbox[name='createAccount']").on('ifUnchecked', function(event){
    //未选中表示不创建
    app.isShow = 0;
    if(empty(aGET.id)){
        $("#Form input[name='username']").val("");
        $("#Form input[name='nickname']").val("");
        $("#Form input[name='password']").val("123456");
    }
});

$('#Form').data('bootstrapValidator', null);
Validator();
function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '名称不能为空'
                    },
                    stringLength: {
                        max: 100,
                        message: '名称长度最多100个字符'
                    },
                }
            },
            wxTel: {
                validators: {
                    notEmpty:{
                        message:'微信绑定手机号不能为空'
                    },
                    phone:{
                        message:'请输入正确的电话号码',
                        country: 'CN'
                    },
                    stringLength: {
                        max: 15,
                        message: '电话号码长度最多15个字符'
                    }
                }
            },
            phone: {
                validators: {
                    notEmpty:{
                        message:'常用号码不能为空'
                    },
                    phone:{
                        message:'请输入正确的电话号码',
                        country: 'CN'
                    },
                    stringLength: {
                        max: 15,
                        message: '电话号码长度最多15个字符'
                    }
                }
            },
            wxCode: {
                validators: {
                    notEmpty:{
                        message:'微信号不能为空'
                    },
                    stringLength: {
                        max: 90,
                        message: '描述长度最多90个字符'
                    }
                }
            },
            deptName: {
                validators: {
                    notEmpty:{
                        message:'请选择部门'
                    }
                }
            },
            stationId: {
                validators: {
                    notEmpty:{
                        message:'请选择职位'
                    }
                }
            },
            username: {
                validators: {
                    notEmpty: {
                        message: '用户名不能为空'
                    },
                    stringLength: {
                        max: 50,
                        message: '用户名长度最多50个字符'
                    },
                }
            },
            nickname: {
                validators: {
                    notEmpty: {
                        message: '昵称不能为空'
                    },
                    stringLength: {
                        max: 1000,
                        message: '昵称长度最多1000个字符'
                    },
                }
            },
            password: {
                validators: {
                    notEmpty: {
                        message: '密码不能为空'
                    },
                    stringLength: {
                        min: 6,
                        /*max: 30,*/
                        message: '密码长度最少6位数'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: '邮箱不能为空'
                    },
                    emailAddress:{
                        message: '邮箱格式不正确'
                    },
                    stringLength: {
                        max: 50,
                        message: '邮箱长度最多50个字符'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if(empty(aGET.id)){
            app.add();
        }else {
            app.update();
        }
    });
}